package br.com.vti.leilao.view.bean;

import br.com.vti.leilao.view.util.JsfManager;
import br.com.vti.leilao.view.util.MessageFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Component;

/**
 * Bean utilizado para detalhar as mensagens de erro.
 * 
 * @author Ednardo Rubens
 * 
 */
@Component
public class ErroBean {

    @Autowired
    @Qualifier("jsfManager")
    private JsfManager jsfManager;
    
    @Autowired
    @Qualifier("messageFactory")
    private MessageFactory messageFactory;

    public JsfManager getJsfManager() {
        return jsfManager;
    }

    public void setJsfManager(JsfManager jsfManager) {
        this.jsfManager = jsfManager;
    }

    public MessageFactory getMessageFactory() {
        return messageFactory;
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }
    
    /**
     * Retorna o StrackTrace de uma mensagem de erro
     * @param exception 
     * @return String erro
     */
    @SuppressWarnings("unchecked")
    public String getStrackTrace(Exception exception) {
        Throwable ex = exception;
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        fillStrackTrace(ex, pw);
        return sw.toString();
    }

    /**
     * Itera sobre um erro
     * @param ex
     * @param pw
     */
    private void fillStrackTrace(Throwable ex, PrintWriter pw) {
        if (ex != null) {
            ex.printStackTrace(pw);
            if (ex instanceof ServletException) {
                Throwable cause = ((ServletException) ex).getRootCause();
                if (cause != null) {
                    pw.println("Root cause:");
                    fillStrackTrace(cause, pw);
                }
            } else if (ex instanceof SQLException) {
                Throwable cause = ((SQLException) ex).getNextException();
                if (cause != null) {
                    pw.println("Next exception:");
                    fillStrackTrace(cause, pw);
                }
            } else {
                Throwable cause = ex.getCause();
                if (cause != null) {
                    pw.println("Cause:");
                    fillStrackTrace(cause, pw);
                }
            }
        }
    }
    
    public void processarErroLogin() {
        HttpSession session = getJsfManager().getHttpRequest().getSession();
        Exception ex = (Exception) session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        if (ex != null) {
            String erro = getMessageFactory().getMessage("erro.tentar.logar");
            if (ex instanceof BadCredentialsException) {
                erro = getMessageFactory().getMessage("erro.usuario.invalido");
            } else if (ex.getCause() != null && ex.getCause() instanceof DisabledException) {
                erro = getMessageFactory().getMessage("erro.usuario.inativo");
            }
            getMessageFactory().addErrorMessage(erro);
        }
        session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
    }
}
